<template>
  <div>
    <!-- 卡片   -->
    <el-card class="box-card">
      <el-form ref="searchForm" :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="用户名" prop="username">
          <el-input size="small" v-model="searchForm.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input size="small" v-model="searchForm.phone" placeholder="手机"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select size="small" v-model="searchForm.sex" placeholder="性别" style="width: 80px">
            <el-option label="-" value=""></el-option>
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期" prop="date">
          <el-date-picker
              size="small"
              v-model="searchForm.date"
              value-format="yyyy-MM-dd"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="onSearch">查询</el-button>
          <el-button size="small" type="primary" @click="resetSearch('searchForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格卡片   -->
    <el-card class="table-card">
      <!-- 表格标题栏 -->
      <div class="table-header">
        <h2 class="table-title">数据列表</h2>
        <div class="table-actions">
          <!-- 新增按钮 -->
          <el-button type="primary" size="mini" class="action-btn" @click="openDialog">
            <i class="el-icon-plus"></i> 新增
          </el-button>
          <el-button type="success" size="mini" class="action-btn" :disabled="ids.length === 0">
            <i class="el-icon-edit"></i> 编辑
          </el-button>
          <!-- 删除按钮 -->
          <el-button type="danger" size="mini" class="action-btn" @click="deleteBatch" :disabled="ids.length === 0">
            <i class="el-icon-delete"></i> 删除
          </el-button>
        </div>
      </div>

      <!-- 表格内容区 -->
      <div class="table-scroll-container">
        <el-table
            :data="tableData"
            border
            style="width: 100%"
            @selection-change="handleSelectionChange"
            highlight-current-row
            row-class-name="table-row"
            :header-cell-style="headerCellStyle"
        >
          <el-table-column
              type="selection"
              width="55"
              align="center"
          ></el-table-column>
          <el-table-column
              prop="id"
              label="编号"
              width="90px"
              sortable
          ></el-table-column>
          <el-table-column
              prop="username"
              label="姓名"
          ></el-table-column>
          <el-table-column
              prop="password"
              label="密码"
          ></el-table-column>
          <el-table-column
              prop="avatar"
              label="头像"
          >
            <template #default="scope">
              <el-image
                  style="width: 50px; height: 50px"
                  :src="scope.row.avatar"
                  :alt="scope.row.first_name + ' ' + scope.row.last_name"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column
              prop="phone"
              label="手机"
          ></el-table-column>
          <el-table-column
              prop="createTime"
              label="注册时间"
          ></el-table-column>
          <el-table-column
              prop="sex"
              label="性别"
              width="60px"
          ></el-table-column>
          <el-table-column
              label="操作"
              align="center"
          >
            <template slot-scope="scope">
              <el-button type="text" size="small" class="operate-btn view-btn">查看</el-button>
              <el-button type="text" size="small" class="operate-btn edit-btn"  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button type="text" size="small" class="operate-btn delete-btn" @click="deleteRow(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>


      <!-- 分页控件 -->
      <div class="table-pagination">
        <el-pagination
            background
            layout="prev, pager, next, sizes, total"
            :total="pageinfo.total"
            :page-size="pageinfo.pageSize"
            :current-page="pageinfo.pageNum"
            :page-sizes="[5, 10, 20, 50]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="userDialogVisible" width="500px">
      <el-form ref="userForm" :rules="rules" :model="userForm" class="custom-user-form" label-position="left" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="userForm.phone" placeholder="手机"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="userForm.sex" placeholder="性别" style="width: 80px">
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="余额" prop="money">
          <el-input v-model="userForm.money" placeholder="余额"></el-input>
        </el-form-item>
        <el-form-item label="生日" prop="createTime">
          <el-date-picker
              v-model="userForm.createTime"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleForm('userForm')">确定</el-button>
          <el-button @click="resetDialogForm('userForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {findUser, delBatch, addUser, editUser} from "@/api/user";

export default {
  name: 'StyledTableCard',
  data() {
    return {
      tableData: [],
      // 搜索表单数据
      searchForm: {
        username: '',
        phone: '',
        sex: null,
        date: [],
        beginDate: null,
        endDate: null,
        pageNum: 1,
        pageSize: 5
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 分页信息
      pageinfo: {
        total: null,
        pages: null,
        pageNum: 1,
        pageSize: 5
      },
      // 批量删除id集合
      ids: [],
      dialogTitle: '添加用户',
      // 对话框可见状态
      userDialogVisible: false,
      userForm: {
        username: '',
        password: '',
        phone: '',
        sex: null,
        money: null
      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    // 获取用户数据
    fetchData() {
      // 发请求
      findUser(this.searchForm).then(res => {
        if (res.code !== '200') {
          this.$message.warning(res.msg);
          this.tableData = [];
        } else {
          this.$message.success('查询用户成功');
          // res是
          this.tableData = res.data.list;
          // 前端展示分页信息
          this.pageinfo.pageSize = res.data.pageSize;
          this.pageinfo.total = res.data.total;
          this.pageinfo.pageNum = res.data.pageNum;
          this.pageinfo.pages = res.data.pages;
        }
      })
    },
    onSearch() {
      this.searchForm.beginDate = this.searchForm.date[0];
      this.searchForm.endDate = this.searchForm.date[1];
      console.log(this.searchForm)
      this.fetchData()
    },
    deleteRow(row) {
      this.ids = [row.id];
      this.deleteBatch();
      console.log('删除的行', row)
    }
    ,
    // 复选框改变
    handleSelectionChange(row) {
      // console.log('选中的行数：', row);
      this.ids = []
      // 组装勾选的行 id数组 , map类似于java的stream流中的map
      row.map(item => {
        this.ids.push(item.id)
      })
      console.log("勾选的行id", this.ids)
    },
    // 改变页面大小
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.fetchData()
      console.log(`每页 ${val} 条`)
    },
    // 改变当前页 (跳转)
    handleCurrentChange(val) {
      this.searchForm.pageNum = val
      this.fetchData()
      console.log(`当前页: ${val}`)
    },
    // 重置搜索表单
    resetSearch(formName) {
      this.$refs[formName].resetFields();
      this.fetchData()
    },
    resetDialogForm(formName) {
      this.$refs[formName].resetFields();
    },
    deleteBatch() {
      this.$confirm('是否确认删除数据编号为[' + this.ids + ']的数据项？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发请求删除
        // this.ids.join(",");// [1,2,3] ==> "1,2,3"
        // 将id数组拼接成字符串
        delBatch({ids: this.ids.join(",")}).then(res => {
          // console.log("删除返回",res)
          if (res.code != 200) {
            this.$message.error("删除失败")
          } else {
            this.$message.success("删除成功")
            this.searchForm.pageNum = 1;
            this.fetchData()
          }
        })
      }).catch(() => {
        this.$message.info("取消删除  ")
      });
    },
    // 打开对话框
    openDialog() {
      this.dialogTitle = '添加';
      this.userDialogVisible = true;
      this.userForm = {}
    },
    // 添加用户逻辑
    handleForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.dialogTitle == "添加"){
            // console.log("添加",this.userForm)
            addUser(this.userForm).then(res => {
              if (res.code != 200){
                this.$message.error("添加失败")
              } else {

                this.$message.success("添加成功")
                this.searchForm.pageNum = 1;
                this.fetchData()
              }
              // 关闭对话
              this.userDialogVisible = false
            })
          } else  {
            editUser(this.userForm).then(res => {
              if (res.code != 200){
                this.$message.error("更新失败")
              } else {
                this.$message.success("更新成功")
                this.searchForm.pageNum = 1;
                this.fetchData()
              }
              // 关闭对话
              this.userDialogVisible = false
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    // 处理更新
    handleEdit(index, row) {
      console.log(index, row);
      this.dialogTitle = "更新"
      this.userDialogVisible = true
      this.userForm = row
    },
  },
  computed: {
    headerCellStyle() {
      return {
        'background-color': '#f5f7fa',
        'color': '#333',
        'font-weight': '500'
      }
    }
  },
  // 生命周期函数
  created() {
    this.fetchData()
  },
}
</script>

<style scoped>
/* 表格滚动容器 */
.table-scroll-container {
  max-height: calc(95vh - 300px); /* 根据实际页面布局调整高度，确保有足够空间显示表格和其他元素 */
  overflow-y: auto; /* 垂直方向超出时显示滚动条 */
}

.box-card {
  width: 100%;
  height: 80px;
}
</style>